package cn.pengpeng.day03.friends;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class FriendsStepOne {

	public static class FriendsStepOneMapper extends Mapper<LongWritable, Text, Text, Text> {

		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			// A:B,C,D,F,E,O
			String[] split = value.toString().split(":");
			String person = split[0];
			String[] friends = split[1].split(",");
			for (String f : friends) {
				context.write(new Text(f), new Text(person));
			}
		}

	}

	public static class FriendsStepOneReducer extends Reducer<Text, Text, Text, Text> {

		@Override
		protected void reduce(Text friend, Iterable<Text> persons, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			StringBuilder sb = new StringBuilder();

			for (Text p : persons) {
				sb.append(p.toString()).append(",");
			}

			context.write(friend, new Text(sb.toString()));

		}

	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);

		job.setJarByClass(FriendsStepOne.class);

		job.setMapperClass(FriendsStepOneMapper.class);
		job.setReducerClass(FriendsStepOneReducer.class);

		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		FileInputFormat.setInputPaths(job, new Path("F:\\mrdata\\friends\\input"));
		FileOutputFormat.setOutputPath(job, new Path("F:\\mrdata\\friends\\out1"));

		job.setNumReduceTasks(1);

		boolean res = job.waitForCompletion(true);
		System.exit(res ? 0 : 1);
	}

}
